package com.shop.controller;

import com.shop.common.Constants;
import com.shop.dto.CarItem;
import com.shop.dto.InvoiceDTO;
import com.shop.model.*;
import com.shop.service.*;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Controller
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private CartService cartService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private GoodsService goodsService;
    // 序列号，用于确保订单编号的唯一性
    private static final AtomicInteger sequence = new AtomicInteger(0);
    // 订单编号格式，例如：yyyyMMddHHmmssSSSS，其中SSSS是序列号
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSS");

    // 获取订单列表
    @GetMapping("/")
    public String orderList(HttpSession session, Model model) {
        User user = (User) session.getAttribute(Constants.Session.USER);
        if (user == null) {
            return "redirect:user/login";
        }
        Integer userId = Math.toIntExact(user.getId());
        List<Order> orders = orderService.getOrdersByUserId(userId);
        model.addAttribute("orders", orders);
        return "views/orders";
    }

    @GetMapping("/order_submit")
    public ModelAndView sbmit(HttpSession session,
                              Model model,
                              @RequestParam("orderId") Integer orderId) {
        ModelAndView mv = new ModelAndView();
        User user = (User) session.getAttribute(Constants.Session.USER);
        if (user == null) {
            mv.setViewName("redirect:/user/login");
        }
        Order order = orderService.selectById(orderId);
        model.addAttribute("orderNo", order.getNo());
        model.addAttribute("totalPrice", order.getTotalMoney());
        model.addAttribute("payType", order.getPayType());
        mv.setViewName("views/order_submit");
        return mv;
    }
    // 提交订单
    @PostMapping("/order_submit")
    public ModelAndView submit(@RequestParam("address") Integer addressId,
                               @RequestParam("payType") String payType,
                               @RequestParam(value = "itemId", required = false)Integer itemId,
                               @RequestParam("goodprice") Double goodprice,
                               @RequestParam (value = "cartId",required = false) Integer cartId,
                               Model model,
                               HttpSession session) {

        ModelAndView mv = new ModelAndView();
        User user = (User) session.getAttribute(Constants.Session.USER);
        if (user == null) {
            mv.setViewName("redirect:/user/login");
        }
        Integer userId = Math.toIntExact(user.getId());
        String orderNo = generateOrderNumber();
//        在数据库写入订单信息
        Order order = new Order();
        order.setGoodid(itemId);
        order.setNo(orderNo);
        order.setUserId(userId);
        order.setAddress(addressService.getAddressById(addressId).getAddress());
        order.setTelphone(addressService.getAddressById(addressId).getPhone());
        order.setPayType(payType);
        order.setAddTime(String.valueOf(LocalDateTime.now()));
//        默认为0，代表待支付订单
        order.setStatus("0");
        if (orderNo != null) {
            // 获取总金额以及支付类型
            Double totalPrice = goodprice;
//            添加order数据
            order.setTotalMoney(totalPrice);
//            删除购物车数据
            cartService.deleteCartbyId(itemId);
            int a=orderService.addOrderInfo(order,cartId);
            if (a <= 0) {
                mv.setViewName("redirect:views/order_add");
            }
            model.addAttribute("orderNo", orderNo);
            model.addAttribute("totalPrice", totalPrice);
            model.addAttribute("payType", payType);
            mv.setViewName("views/order_submit");
        }
        return mv;
    }


    @PostMapping ("/alipay/pay")
    @ResponseBody
    public String alipayPay(String orderId, HttpSession session) {
        log.info("orderId:{}",orderId);

        User user = (User) session.getAttribute(Constants.Session.USER);
        if (user == null) {
            return "redirect:/user/login";
        }
        session.setAttribute("orderId",orderId);
        Integer userId = Math.toIntExact(user.getId());
//        Double totalPrice = cartService.getTotalPrice(userId).getPrice();
        Double totalPrice = orderService.selectByOrderNo(orderId).getTotalMoney();
        String form = orderService.createAlipayPayment(orderId, totalPrice, "支付订单号：" +orderId);
        return form;
    }

    @PostMapping("/alipay/notify")
    public String alipayNotify(@RequestParam String trade_status,
                               @RequestParam String out_trade_no,
                               @RequestParam String trade_no,
                               HttpSession session) {
        System.out.println("支付回调已收到：状态: " + trade_status + " 订单号：" + out_trade_no);
        if ("TRADE_SUCCESS".equals(trade_status)) {
            Integer userId = Math.toIntExact(((User) session.getAttribute(Constants.Session.USER)).getId());
            orderService.orderSuccess(out_trade_no, userId);
            return "views/order_pay_success";
        }
        return "views/order_pay_fail";
    }

    @GetMapping("/alipay/return")
    public String alipayReturn(HttpSession session,Model model) {
        User user = (User) session.getAttribute(Constants.Session.USER);
        if (user == null) {
            return "redirect:/user/login";
        }
        Integer userId = Math.toIntExact(user.getId());
        String orderId = (String) session.getAttribute("orderId");
        orderService.orderSuccess(orderId, userId);
        model.addAttribute("orderNo",orderId);
        return "views/order_pay_success";
    }

    // 删除订单
    @PostMapping("/delete")
    public String deleteOrder(@RequestParam("orderId") Integer id) {
        boolean success = orderService.deleteOrder(id);
        if (success) {
            return "redirect:/order/";
        }
        return "error/500";
    }


    // 添加订单页面
    @GetMapping("/order_add")
    public String addOrder(
            @RequestParam("goodId") Integer goodId,
            @RequestParam(value = "cartId", required = false) Integer cartId,
            @RequestParam("count") Integer count,
            Model model,
            HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        User user = (User) session.getAttribute(Constants.Session.USER);
        if (user == null) {
            return "user/login";
        }
        List<Address> addresses = addressService.selectByUserId(Math.toIntExact(user.getId()));
        if (cartId!=null){// 获取地址列表
            // 获取购物车数据
            CarItem carItems = cartService.getCartItem(cartId);
            model.addAttribute("cartItems", carItems);

            // 获取总价格
//        Double totalPrice = cartService.getTotalPrice(Math.toIntExact(user.getId()));
//        model.addAttribute("totalPrice", totalPrice);
//        model.addAttribute("carItems", carItems);
            model.addAttribute("addresses", addresses);
            return "views/order_add";
        }else {
            Goods goods = goodsService.selectById(goodId);
            CarItem carItems =new CarItem();
            carItems.setGoodid(goodId);
            carItems.setGoodimage(goods.getImage());
            carItems.setGoodname(goods.getName());
            // 示例：显式类型转换
            // 将 BigDecimal 转换为 double，再进行乘法运算
            Double totalPrice = goods.getSalePrice().doubleValue() * count;
            carItems.setGoodprice(totalPrice);
            carItems.setNum(count);
            model.addAttribute("cartItems", carItems);
            model.addAttribute("addresses", addresses);
            return "views/order_add";
        }
    }



    @GetMapping("/invoice")
    public ModelAndView invoice(@RequestParam Integer orderId, RedirectAttributes redirectAttributes ){
        ModelAndView modelAndView=new ModelAndView();
//        Order order=orderService.selectById(orderId);
//        modelAndView.addObject("order",order);
        Invocei invocei=orderService.getInvoiceByOrderId(orderId);
        if(invocei!=null)  return new ModelAndView("redirect:invoice/show?id="+invocei.getId());
        InvoiceDTO invoiceDTO=orderService.getInvoiceDTO(orderId);
        modelAndView.addObject("order",invoiceDTO);
        modelAndView.setViewName("views/invoice1");
        return modelAndView;
    }

    @PostMapping("/invoice/add")
    public ModelAndView invoiceAdd(@RequestParam Map map){
        log.info("map:{}",map);
        Integer id=orderService.addInvoice(map);
        return new ModelAndView("redirect:show?id="+id);
    }

    @GetMapping("/invoice/show")
    public ModelAndView invoiceShow(@RequestParam Integer id){
        ModelAndView modelAndView=new ModelAndView();
        Invocei invocei=orderService.getInvoice(id);
        Order order=orderService.selectById(invocei.getOrderId());
        modelAndView.addObject("invoice",invocei);
        modelAndView.addObject("no",order.getNo());
        modelAndView.setViewName("views/invoiceShow");
        return modelAndView;
    }

    public static String generateOrderNumber() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 格式化日期时间
        String dateTimePart = now.format(formatter);
        // 获取序列号并递增
        int seq = sequence.getAndIncrement();
        // 生成订单编号
        return dateTimePart + seq;
    }

}

